#-------------------------------------------------------------------------------
# Name:        Tumb
# Purpose:
#
# Author:      Kyu
#
# Created:     19/11/2013
# Copyright:   (c) Kyu 2013
# Licence:     <your licence>
#-------------------------------------------------------------------------------
#Source:
#!/usr/bin/env python
import urllib,re,os,urllib2
path=os.getcwd()
print path
# get the url
daUrl = raw_input('Url please:')
cut = raw_input('Wanna cutoff? @ (eg:March 2011):')
##daUrl='http://comegirls.tumblr.com/archive/2010/12'
source = urllib.urlopen(daUrl).read()
spl=daUrl.split('/')
spl.insert(-2,spl[2].split('.')[0])
#Create the folder or check for preesisting
fold='_'.join(spl[-3:])
##fold=spl[-3]
folder=fold;
##for folder in spl[-4:]: # became an unnecessary thing coz of MkDirSSS
if not os.path.exists(folder):
  os.makedirs(folder)

#image hunt
nex=re.findall('/'+'/'.join(daUrl.split('/')[-3:])+'(\?before_time=.*)\">Next',source)
i=0;imgs=[];prev='';dont=0;
datee=re.findall('<h2 class="date">(.*)</h2>',source)
if datee!=[]:
   print datee[0]
   k=datee[0]
   imgs.append([datee[0]])
else: print 'No Date..'
got = re.findall('=[\'|\"](http://.*\.jpg)[\'|\"]>',source);
imgs.append(got)
while nex!=[]:
    i=i+1;print 'page '+str(i+1)

##    datee=re.findall('<h2 class="date">(.*)</h2>',source)
##    if datee!=[]:
##       if i==1:m=0;
##       if len(datee)>1:
##          print 'hmm.. more pages in one :',datee
##          m=datee.index(k)+1;
##          print datee[m]
##          k=datee[m]
##          imgs.append([datee[m]])

    source = urllib.urlopen(daUrl+nex[0]).read()
    got = re.findall('=[\'|\"](http://.*\.jpg)[\'|\"]>',source)
    imgs.append(got)
    nex=re.findall('/'+'/'.join(daUrl.split('/')[-3:])+'(\?before_time=.*)\">Next',source)
    datee=re.findall('<h2 class="date">(.*)</h2>',source)
    if datee!=[]:
       if cut!='':
          if prev==cut: print 'yup.. Cutoff Reached! for : '+cut; break
       if datee[0]!=prev:print datee[0]
       imgs.append([datee[0]])
       chec=int(datee[0].split(' ')[1])
       prev=datee[0]
       if chec<int(spl[-2]):print str(chec)+' is lesser than '+str(spl[-2]);break;
    else: print 'No Date found dude.. quittin'

checks=['1280.jpg','500.jpg','400.jpg','250.jpg']
name=['']
##print imgs
tots=len(imgs)/2;print str(tots)+' pages for this SeSSiOn..\n \t hmm.. lets get started!'
for imgg in imgs:
  tot=len(imgg)
  if tot==1:
     kk=imgg[0].split(' ')
     folder=fold+'/'+kk[0][:3]+' '+kk[1];dont=1;
     if not os.path.exists(folder):
        os.makedirs(folder);print folder+' created hai.......\n\n'
     else: print ' Already Gone!'
     #break#(Not the brightest of ideas!)
  else:
       print str(tots)+' pages left to go and '+str(tot)+' in this page'
       tots=tots-1;dont=0;
  for img in imgg:
##    url=img
      if dont==1:break;
      name=[str(tots+1)+'_'+str(tot)]
      tot=tot-1;# print tot;
      #name=[str(tot)];

      for nam in checks:
            img='_'.join(img.split('_')[:-1])+'_'+nam
            try:
                test = urllib2.urlopen(urllib2.Request(img))
                break
            except:
                continue
      filename = name[0]+'_'+img.split('/')[-1]
      if not os.path.exists(path+'/'+folder+'/'+filename):
          urllib.urlretrieve(img,folder+'/'+filename)
          print str(tot)+' - '+filename+' addedz'
      else:
           print filename+' already exists'
           break
##       i=1
##       while os.path.exists(path+'/'+folder+'/'+filename):
##             i=i+1;filename=filename.replace('.','--'+str(i)+'.')
##       urllib.urlretrieve(img,folder+'/'+filename)
##       print filename+' created'
print 'Yup.. '+daUrl+' Done!'